import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QDialogButtonBox
from functools import partial
from Common import Log
import DialogResult
import subprocess
import os
import shutil
from Common import DownloadThread
from Common import ADKUtils
from Common import AptInstallThread
from Common import MakeSDThread
from Common import ReadLogThread
from Common import PIPInstallThread
from Common import ExecuteCommandThread
import collections
import encodings.idna


class MindStudioInstall:

    def __init__(self, ui):

        # self.project_path = os.path.split(os.path.realpath(__file__))[0]
        self.project_path = os.path.dirname(os.path.abspath(sys.argv[0]))

        self.download_path = os.environ.get("HOME")

        self.logfile = os.path.join(self.project_path, "install_mindstudio.log")

        if os.path.exists(self.logfile):
            shutil.move(self.logfile, self.logfile + ".old")

        # self.ui = MindStudio.Ui_MainWindow()
        self.ui = ui
        self.sudo_passwd = ADKUtils.read_decode_func(self.project_path)
        self.end_thread = 'pip3'
        self.apt_all_done = False
        self.pip2_all_done = False
        self.pip3_all_done = False
        self.download_ok = False
        self.ms_install_not_running = True
        self.logger = Log(self.logfile, __name__).getlog()

        self.logger.info('Install Mind Studio Page....')

        (ret, output) = subprocess.getstatusoutput("whoami")

        self.logger.info('the user is %s' % output)

        self.logger.info("project dir: " + self.project_path)
        self.logger.info("download dir: " + self.download_path)

        self.download_thread_list = []
        self.apt_thread_list = []
        self.pip2_thread_list = []
        self.pip3_thread_list = []
        self.source_flag_dict = collections.OrderedDict()
        self.source_flag_dict["use the default apt-get source"] = [False]
        self.source_flag_dict["use the http://mirrors.huaweicloud.com/ apt-get source"] = [False]
        self.source_flag_dict["use the https://mirrors.tuna.tsinghua.edu.cn/ubuntu/apt-get source"] = [False]
        self.source_flag_dict["use the http://mirrors.aliyun.com/ubuntu/ apt-get source"] = [False]
        self.source_flag_dict["use the http://mirrors.ustc.edu.cn/ubuntu/ apt-get source"] = [False]
        self.comboBox_tar = self.ui.comboBox_tar

    def download(self, key):
        download_url = self.ui.download_dict[key]['url']
        path = self.download_path
        self.download_thread = DownloadThread(download_url, path, key, checkBox_tar_update_source=self.comboBox_tar, buffer=10240, project_dir=self.project_path)
        self.download_thread.download_progress_signal.connect(self.change_progressbar_value)
        self.download_thread.download_finished_signal.connect(self.do_download_finished)
        self.download_thread.start()

        self.download_thread_list.append(self.download_thread)

    def change_progressbar_value(self, value, key):
        self.ui.download_dict[key]["progressBar"].setValue(value)

    def do_download_finished(self, value, key):
        if value == 2:
            self.ui.download_dict[key]["statusLabel"].setText("failed")
            self.ui.download_dict[key]["progressBar"].setValue(0)
            self.logger.info("%s download failed." % key)
            self.ui.download_dict[key]["download_finished"] = False
        elif value == 1:
            self.ui.download_dict[key]["statusLabel"].setText("download_finished")
            self.ui.download_dict[key]["progressBar"].setValue(100)
            self.logger.info("%s download finished." % key)
            self.ui.download_dict[key]["download_finished"] = True
        elif value == 3:
            self.ui.download_dict[key]["statusLabel"].setText("running")
            self.logger.info("%s download running." % key)
            self.ui.download_dict[key]["download_finished"] = False
            return
        elif value == 4:
            self.ui.download_dict[key]["statusLabel"].setText("pause")
            self.logger.info("%s download pause." % key)
            self.ui.download_dict[key]["download_finished"] = False
            return
        self.ui.download_dict[key]["statusLabel"].setVisible(True)

        Flag = True
        for key in self.ui.download_dict:
            if self.ui.download_dict[key]["statusLabel"].text() != "download_finished":
                if self.ui.download_dict[key]["statusLabel"].text() != "failed":
                    Flag = False
        if Flag:
            self.do_download_ok()

    def do_download_ok(self):
        self.download_ok = True
        if self.apt_all_done and self.pip2_all_done and self.pip3_all_done and self.ms_install_not_running:
            self.ms_install_not_running = False
            self.install_ms_impl()

    def down_packages(self):
        self.logger.info("Begin to download packages...")
        self.download_ok = False
        for key in self.ui.download_dict:
            self.ui.download_dict[key]["download_finished"] = False
            self.ui.download_dict[key]["statusLabel"].setText("")
        for key in self.ui.download_dict:
            self.download(key)

    def do_apt_install(self, key, bFinished):
        self.logger.info("in do_apt_install.")

        if(bFinished):
            self.ui.apt_install_dict[key]["statusLabel"].setText("finished.")
            self.logger.info("install " + key + " finished.")
            self.ui.apt_install_dict[key]["progressBar"].setMaximum(100)
            self.ui.apt_install_dict[key]["progressBar"].setValue(100)

        else:
            self.ui.apt_install_dict[key]["statusLabel"].setText("failed.")
            self.logger.error("install " + key + " failed.")
            self.ui.apt_install_dict[key]["progressBar"].setMaximum(100)
            self.ui.apt_install_dict[key]["progressBar"].setValue(50)

    def do_apt_install_begin(self, key):
        self.ui.apt_install_dict[key]["statusLabel"].setText("running.")
        self.logger.info("install " + key + " begin.")
        self.ui.apt_install_dict[key]["progressBar"].setMaximum(0)

    def do_apt_update_begin(self, key):
        if key == "update":
            self.ui.apt_update_label.setText("running")
            self.ui.progressBar_apt_update.setMaximum(0)
            self.logger.info("apt-get update begin.")
        else:
            self.logger.info("it's not apt-get update running. ")

    def do_apt_update(self, key, bFinished):
        if key == "update":

            if (bFinished == 1):
                self.ui.apt_update_label.setText("finished")
                self.logger.info("apt-get " + key + " finished.")
                self.ui.progressBar_apt_update.setMaximum(100)
                self.ui.progressBar_apt_update.setValue(100)
                self.source_flag_dict[self.ui.comboBox_apt.currentText()] = [True]
            elif(bFinished == 2):
                self.ui.apt_update_label.setText("pass")
                self.logger.info("apt-get " + key + " pass.")
                self.ui.progressBar_apt_update.setMaximum(100)
                self.ui.progressBar_apt_update.setValue(100)
            else:
                self.ui.apt_update_label.setText("failed")
                self.logger.error("apt-get " + key + " failed.")
                self.ui.progressBar_apt_update.setMaximum(100)
                self.ui.progressBar_apt_update.setValue(50)
                self.ui.pushButton_pause.setEnabled(False)
                self.ui.pushButton_pause.setVisible(False)
                self.ui.pushButton.setEnabled(True)
                self.ui.pushButton.setVisible(True)
                ADKUtils.disable_item_comboBox(self.ui.comboBox_pip2, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
                ADKUtils.disable_item_comboBox(self.ui.comboBox_pip3, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
                ADKUtils.disable_item_comboBox(self.ui.comboBox_apt, [0, 1, 2, 3, 4, 5], 1 | 32)
                ADKUtils.disable_item_comboBox(self.ui.comboBox_tar, [0, 1, 2], 1 | 32)

        else:
            self.logger.error("it's not apt-get update. ")
            self.ui.pushButton_pause.setEnabled(False)
            self.ui.pushButton_pause.setVisible(False)
            self.ui.pushButton.setEnabled(True)
            self.ui.pushButton.setVisible(True)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip2, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip3, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_apt, [0, 1, 2, 3, 4, 5], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_tar, [0, 1, 2], 1 | 32)

    def do_apt_already_installed(self, key):
        self.ui.apt_install_dict[key]["statusLabel"].setText("already installed.")
        self.logger.info(key + " already installed.")
        self.ui.apt_install_dict[key]["progressBar"].setMaximum(100)
        self.ui.apt_install_dict[key]["progressBar"].setValue(100)
        self.ui.apt_install_dict[key]["isInstalled"] = True

    def apt_install(self):

        apt_thread = AptInstallThread(self.ui.apt_install_list, self.logfile,
                     checkBox_apt_update_source=self.ui.comboBox_apt, b_sudo=True, passwd=self.sudo_passwd, mylogger=self.logger, source_dict=self.source_flag_dict)
        apt_thread.apt_install_signal.connect(self.do_apt_install)
        apt_thread.apt_install_begin_signal.connect(self.do_apt_install_begin)
        apt_thread.apt_update_begin_signal.connect(self.do_apt_update_begin)
        apt_thread.apt_update_signal.connect(self.do_apt_update)
        apt_thread.apt_already_installed.connect(self.do_apt_already_installed)

        apt_thread.apt_all_have_done.connect(self.do_apt_all_have_done)
        apt_thread.start()

        self.apt_thread_list.append(apt_thread)

    def do_apt_all_have_done(self):
        self.apt_all_done = True

        self.pip2_install()
        self.pip3_install()

        if self.apt_all_done and self.pip2_all_done and self.pip3_all_done and self.ms_install_not_running:
            self.ms_install_not_running = False
            self.install_ms_impl()

    def is_apt_install_already(self):
        for key in self.ui.apt_install_list[1:]:
            if not ADKUtils.is_apt_installed(key):
                self.logger.info(key + " not ready.")
                return False
        self.logger.info("all apt install finished.")
        return True

    def is_download_already(self):
        for key in self.ui.download_dict:
            if not self.ui.download_dict[key]["download_finished"]:
                return False
        self.logger.info("all package downloaded finished.")
        return True

    def is_pip3_install_already(self):
        for key in self.ui.pip3_install_dict:
            if key == 'pip3_upgrade':
                continue
            if not ADKUtils.is_pip_installed(key, pip2=False):
                return False
        self.logger.info("all pip3 install finished.")
        return True

    def is_pip2_install_already(self):
        for key in self.ui.pip2_install_dict:
            if key == 'pip2_upgrade':
                continue
            if not ADKUtils.is_pip_installed(key):
                return False
        self.logger.info("all pip2 install finished.")
        return True

    def is_all_ready(self):
        return self.is_apt_install_already() and self.is_download_already() and self.is_pip2_install_already() and self.is_pip3_install_already()

    def pip2_install(self):

        for item in self.ui.pip2_install_list:
            if self.ui.comboBox_pip2.currentText() == "use the default sources":
                continue
            item[1] = item[1] + " -i " + self.ui.comboBox_pip2.currentText()

        if self.ui.checkBox_pip3_upgrade.isChecked():
            pip2_thread = PIPInstallThread(self.ui.pip2_install_list, self.logfile, pip2=True, passwd=self.sudo_passwd, mylogger=self.logger)
        else:
            pip2_thread = PIPInstallThread(self.ui.pip2_install_list[1:], self.logfile, pip2=True, passwd=self.sudo_passwd, mylogger=self.logger)

        pip2_thread.install_signal.connect(self.do_pip2_install)
        pip2_thread.install_begin_signal.connect(self.do_pip2_install_begin)
        pip2_thread.already_installed.connect(self.do_pip2_already_installed)
        pip2_thread.pip2_all_have_done.connect(self.pip2_all_have_done)
        pip2_thread.start()

        self.pip2_thread_list.append(pip2_thread)

    def pip2_all_have_done(self):
        self.pip2_all_done = True
        if self.apt_all_done and self.download_ok and self.pip3_all_done and self.ms_install_not_running:
            self.ms_install_not_running = False
            self.install_ms_impl()

    def do_pip2_install(self, key, bFinished):
        if (bFinished):
            self.ui.pip2_install_dict[key]["statusLabel"].setText("finished.")
            self.logger.info("pip2 install " + key + " finished.")
            self.ui.pip2_install_dict[key]["progressBar"].setMaximum(100)
            self.ui.pip2_install_dict[key]["progressBar"].setValue(100)
            self.ui.pip2_install_dict[key]["isInstalled"] = True
        else:
            self.ui.pip2_install_dict[key]["statusLabel"].setText("failed.")
            self.logger.error("pip2 install " + key + " failed.")
            self.ui.pip2_install_dict[key]["progressBar"].setMaximum(100)
            self.ui.pip2_install_dict[key]["progressBar"].setValue(50)

    def do_pip2_install_begin(self, key):
        self.ui.pip2_install_dict[key]["statusLabel"].setText("running.")
        self.logger.info("pip2 install " + key + " begin.")
        self.ui.pip2_install_dict[key]["progressBar"].setMaximum(0)

    def do_pip2_already_installed(self,key):

        self.ui.pip2_install_dict[key]["statusLabel"].setText("already installed.")
        self.logger.info(key + " already installed.")
        self.ui.pip2_install_dict[key]["progressBar"].setMaximum(100)
        self.ui.pip2_install_dict[key]["progressBar"].setValue(100)
        self.ui.pip2_install_dict[key]["isInstalled"] = True

    def pip3_install(self):

        for item in self.ui.pip3_install_list:
            if self.ui.comboBox_pip3.currentText() == "use the default sources":
                continue
            item[1] = item[1] + " -i " + self.ui.comboBox_pip3.currentText()

        if self.ui.checkBox_pip2_upgrade.isChecked():
            pip3_thread = PIPInstallThread(self.ui.pip3_install_list, self.logfile, pip2=False, passwd=self.sudo_passwd, mylogger=self.logger)
        else:
            pip3_thread = PIPInstallThread(self.ui.pip3_install_list[1:], self.logfile, pip2=False, passwd=self.sudo_passwd, mylogger=self.logger)

        pip3_thread.install_signal.connect(self.do_pip3_install)
        pip3_thread.install_begin_signal.connect(self.do_pip3_install_begin)
        pip3_thread.already_installed.connect(self.do_pip3_already_installed)
        pip3_thread.pip3_all_have_done.connect(self.pip3_all_have_done)
        pip3_thread.start()

        self.pip3_thread_list.append(pip3_thread)

    def pip3_all_have_done(self):
        self.pip3_all_done = True
        if self.apt_all_done and self.download_ok and self.pip2_all_done and self.ms_install_not_running:
            self.ms_install_not_running = False
            self.install_ms_impl()

    def do_pip3_install(self, key, bFinished):

        if (bFinished):
            self.ui.pip3_install_dict[key]["statusLabel"].setText("finished.")
            self.logger.info("pip3 install " + key + " finished.")
            self.ui.pip3_install_dict[key]["progressBar"].setMaximum(100)
            self.ui.pip3_install_dict[key]["progressBar"].setValue(100)
            self.ui.pip3_install_dict[key]["isInstalled"] = True
        else:
            self.ui.pip3_install_dict[key]["statusLabel"].setText("failed.")
            self.logger.error("pip3 install " + key + " failed.")
            self.ui.pip3_install_dict[key]["progressBar"].setMaximum(100)
            self.ui.pip3_install_dict[key]["progressBar"].setValue(50)

    def do_pip3_install_begin(self, key):
        self.ui.pip3_install_dict[key]["statusLabel"].setText("running.")
        self.logger.info("pip3 install " + key + " begin.")
        self.ui.pip3_install_dict[key]["progressBar"].setMaximum(0)

    def do_pip3_already_installed(self,key):
        self.ui.pip3_install_dict[key]["statusLabel"].setText("already installed.")
        self.logger.info(key + " already installed.")
        self.ui.pip3_install_dict[key]["progressBar"].setMaximum(100)
        self.ui.pip3_install_dict[key]["progressBar"].setValue(100)
        self.ui.pip3_install_dict[key]["isInstalled"] = True  

    def check_if_need_reinstall(self):

        if os.path.exists(os.path.join(os.environ["HOME"], "MindStudio-ubuntu/bin/MindStudio.sh")):
            return self.show_message_with_result("you have already installed MindStudio, do you want to reinstall MindStudio?!")
        else:
            return True

    def install_ms_prepare(self):

        apt_update = self.ui.comboBox_apt.currentText()
        pip2_sources = self.ui.comboBox_pip2.currentText()
        pip3_sources = self.ui.comboBox_pip3.currentText()
        if apt_update == "" or pip2_sources == "" or pip3_sources == "":
            ADKUtils.show_message("apt sources or pip sources is empty, please choose a sources in the drop-down box.")
            self.logger.info('apt sources or pip sources is empty, please choose a sources in the drop-down box.')
            return

        self.logger.info("Begin to prepare for install Mindstudio")

        print("start install_ms_prepare")
        self.ui.progressBar_ms_install.setValue(0)
        self.ui.pushButton.setEnabled(False)
        self.ui.pushButton.setVisible(False)
        self.ui.pushButton_pause.setEnabled(True)
        self.ui.pushButton_pause.setVisible(True)
        ADKUtils.disable_item_comboBox(self.ui.comboBox_pip2, [0, 1, 2, 3, 4, 5, 6], 0)
        ADKUtils.disable_item_comboBox(self.ui.comboBox_pip3, [0, 1, 2, 3, 4, 5, 6], 0)
        ADKUtils.disable_item_comboBox(self.ui.comboBox_apt, [0, 1, 2, 3, 4, 5], 0)
        ADKUtils.disable_item_comboBox(self.ui.comboBox_tar, [0, 1, 2], 0)

        if not self.check_if_need_reinstall():
            self.ui.pushButton_pause.setEnabled(False)
            self.ui.pushButton_pause.setVisible(False)
            self.ui.pushButton.setEnabled(True)
            self.ui.pushButton.setVisible(True)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip2, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip3, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_apt, [0, 1, 2, 3, 4, 5], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_tar, [0, 1, 2], 1 | 32)
            return

        self.apt_all_done = False
        self.pip2_all_done = False
        self.pip3_all_done = False

        self.apt_install()

        self.down_packages()

    def is_finished(self):
        for item in self.download_thread_list:
            if item.isFinished() == False:
                return False
        for item in self.apt_thread_list:
            if item.isFinished() == False:
                return False
        for item in self.pip2_thread_list:
            if item.isFinished() == False:
                return False
        for item in self.pip3_thread_list:
            if item.isFinished() == False:
                return False
        return True

    def update_log(self, msg):
        if msg.find('[ERROR]') != -1:
            msg = "<font color='red'>"+ msg +'</font>'
        self.ui.textBrowser_log.append(msg)

        if msg.find('MindStudio-ubuntu/plugins/python-ce/helpers/py3only/docutils/parsers/rst/include/README.txt') != -1:
            self.ui.progressBar_ms_install.setValue(15)

        if msg.find('MindStudio-ubuntu/plugins/python-ce/helpers/pydev/pycharm-readme.txt') != -1:
            self.ui.progressBar_ms_install.setValue(20)

        if msg.find('MindStudio-ubuntu/plugins/python-ce/helpers/virtualenv-16.4.3.tar.gz') != -1:
            self.ui.progressBar_ms_install.setValue(30)

        if msg.find('MindStudio-ubuntu/tools/cmake/share/cmake-3.13/Help/module/CSharpUtilities.rst') != -1:
            self.ui.progressBar_ms_install.setValue(40)

        if msg.find('MindStudio-ubuntu/tools/cmake/share/cmake-3.13/Help/prop_tgt/NO_SONAME.rst') != -1:
            self.ui.progressBar_ms_install.setValue(50)

        if msg.find('MindStudio-ubuntu/tools/cmake/share/cmake-3.13/Modules/Compiler/ARMCC-ASM.cmake') != -1:
            self.ui.progressBar_ms_install.setValue(60)

        if msg.find('MindStudio-ubuntu/tools/cmake/share/cmake-3.13/Modules/Platform/Android/ndk-stl-system.cmake') != -1:
            self.ui.progressBar_ms_install.setValue(70)

    def read_log_to_gui(self, logfile):

        self.read_log_thread = ReadLogThread(logfile)

        self.read_log_thread.update_log_signal.connect(self.update_log)

        self.read_log_thread.start()

    def show_message(self, msg):
        dialog_result = QDialog()
        result_ui = DialogResult.Ui_Dialog()
        result_ui.setupUi(dialog_result)
        result_ui.label.setText(msg)

        return dialog_result.exec() == QDialog.Accepted

    def show_message_with_result(self, msg):
        dialog_result = QDialog()
        result_ui = DialogResult.Ui_Dialog()
        result_ui.setupUi(dialog_result)
        result_ui.label.setText(msg)
        result_ui.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)

        return dialog_result.exec() == QDialog.Accepted

    def read_agreement(self, dialog_agreement):

        if dialog_agreement.exec() == QDialog.Accepted:
            self.logger.info("you agree all the agreement of the package you download.")
            self.ui.checkBox_aggrement.setChecked(True)
            self.ui.pushButton.setEnabled(True)
        else:
            self.ui.checkBox_aggrement.setChecked(False)

        return

    def do_export_java_env(self):

        if not (("JAVA_HOME" in os.environ) and os.environ["JAVA_HOME"] == "/usr/lib/jvm/java-8-openjdk-amd64"):
            self.logger.info("echo \"export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\" >> $HOME/.bashrc")
            subprocess.getstatusoutput("echo \"export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\" >> $HOME/.bashrc")

            self.logger.info("echo \"export PATH=\$JAVA_HOME/bin:\$PATH\" >> $HOME/.bashrc")
            subprocess.getstatusoutput("echo \"export PATH=\$JAVA_HOME/bin:\$PATH\" >> $HOME/.bashrc")

            self.logger.info("source $HOME/.bashrc")
            subprocess.getstatusoutput("source $HOME/.bashrc")

    def do_install_ms_begin(self):
        self.ui.progressBar_ms_install.setValue(5)
        self.show_message("start install MindStudio, please wait....")

    def do_install_ms_end(self, bResult):
        if bResult:
            self.ui.progressBar_ms_install.setMaximum(100)
            self.ui.progressBar_ms_install.setValue(100)
            if self.show_message_with_result("Mind Studio will be started, please continue install DDK on Mind Studio."):
                self.start_ms_thread = ExecuteCommandThread("$HOME/MindStudio-ubuntu/bin/MindStudio.sh & ")
                self.start_ms_thread.start()
            self.ui.pushButton.setEnabled(True)
            self.ui.pushButton.setVisible(True)
            self.ms_install_not_running = True
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip2, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip3, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_apt, [0, 1, 2, 3, 4, 5], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_tar, [0, 1, 2], 1 | 32)
        else:
            self.ui.progressBar_ms_install.setMaximum(100)
            self.ui.progressBar_ms_install.setValue(10)
            self.show_message("MindStudio install failed, maybe your package download error, please delete it manually and download again.")
            self.ms_install_not_running = True
            self.ui.pushButton.setEnabled(True)
            self.ui.pushButton.setVisible(True)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip2, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip3, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_apt, [0, 1, 2, 3, 4, 5], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_tar, [0, 1, 2], 1 | 32)

    def install_ms_impl(self):
        if not self.is_all_ready():
            self.logger.info("not ready, not all packages installed, or not all packages downloaded, please check. \nYou may need to change sources and try again")
            self.show_message("not ready, not all packages installed, or not all packages downloaded, please check. \nYou may need to change sources and try again")
            self.ui.pushButton_pause.setVisible(False)
            self.ui.pushButton_pause.setEnabled(False)
            self.ui.pushButton.setVisible(True)
            self.ui.pushButton.setEnabled(True)
            # self.ui.pushButton.setEnabled(True)
            self.ms_install_not_running = True
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip2, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip3, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_apt, [0, 1, 2, 3, 4, 5], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_tar, [0, 1, 2], 1 | 32)
            return
        self.ui.pushButton_pause.setVisible(False)
        self.ui.pushButton_pause.setEnabled(False)
        self.ui.pushButton.setEnabled(False)
        self.ui.pushButton.setVisible(True)


        if not self.show_message_with_result("Begin to install Mind Studio for you, if you don't need, you can cancel."):
            self.ui.pushButton.setEnabled(True)
            self.ms_install_not_running = True
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip2, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_pip3, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_apt, [0, 1, 2, 3, 4, 5], 1 | 32)
            ADKUtils.disable_item_comboBox(self.ui.comboBox_tar, [0, 1, 2], 1 | 32)
            return

        self.do_export_java_env()
        self.ms_install_not_running = False

        self.install_ms_thread = ExecuteCommandThread("mv $HOME/MindStudio-ubuntu $HOME/MindStudio-ubuntu_bak; tar -zxvf $HOME/mindstudio.tar.gz -C $HOME >> " + self.logfile)
        self.install_ms_thread.execute_begin.connect(self.do_install_ms_begin)
        self.install_ms_thread.execute_end.connect(self.do_install_ms_end)

        self.install_ms_thread.start()

    def prepare_pause(self):
        for t in self.download_thread_list:
            t.stop_flag = True
            self.logger.info("stop download thread, t.stop_flag=%s", t.stop_flag)


        for t in self.apt_thread_list:
            t.stop_flag = True
            self.logger.info("stop apt thread, t.stop_flag=%s", t.stop_flag)

        for t in self.pip3_thread_list:
            t.stop_flag = True
            self.logger.info("stop pip3 thread, t.stop_flag=%s", t.stop_flag)

        for t in self.pip2_thread_list:
            t.stop_flag = True
            self.logger.info("stop pip2 thread, t.stop_flag=%s", t.stop_flag)
            self.logger.info("stop pip2 thread, t.stop_flag=%s", t.stop_flag)

        self.ui.pushButton_pause.setEnabled(False)
        self.ui.pushButton_pause.setVisible(False)
        self.ui.pushButton.setEnabled(True)
        self.ui.pushButton.setVisible(True)
        ADKUtils.disable_item_comboBox(self.ui.comboBox_pip2, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
        ADKUtils.disable_item_comboBox(self.ui.comboBox_pip3, [0, 1, 2, 3, 4, 5, 6], 1 | 32)
        ADKUtils.disable_item_comboBox(self.ui.comboBox_apt, [0, 1, 2, 3, 4, 5], 1 | 32)
        ADKUtils.disable_item_comboBox(self.ui.comboBox_tar, [0, 1, 2], 1 | 32)

